(function () {
    var $MultiPicUpload = function (options) {
        var settings = $.extend({}, $MultiPicUpload.defaults, options);
        this.uploadUrl = Feng.ctxPath + settings.url;
        this.fileSizeLimit = settings.fileSizeLimit;
        this.multiple = settings.multiple;
        this.pickBtnId = settings.pickBtnId;
        this.uploadBtnId = settings.uploadBtnId;
    };

    $MultiPicUpload.defaults = {
        url: "/mgr/upload",
        fileSizeLimit: 100 * 1024 * 1024,
        multiple: true,
        pickBtnId: "goodsUpload"

    }

    $MultiPicUpload.prototype = {
        /**
         * 初始化webUploader
         */
        init: function () {
            var uploader = this.create();
            this.bindEvent(uploader);
            this.bindUploadBtn(uploader);
            return uploader;
        },
        /**
         * 创建webuploader对象
         */
        create: function () {
            var webUploader = WebUploader.create({
                auto: false,
                pick: {
                    id: '#' + this.pickBtnId,
                    // multiple: this.multiple, //是否支持上传多个
                    label: ""
                },
                accept: {
                    title: 'Images',
                    extensions: 'gif,jpg,jpeg,bmp,png',
                    mimeTypes: 'image/gif,image/jpg,image/jpeg,image/bmp,image/png'
                },
                //文件上传方式
                method: "POST",
                swf: Feng.ctxPath + '/static/css/plugins/webuploader/Uploader.swf',
                disableGlobalDnd: true,
                duplicate: true,
                server: this.uploadUrl,
                //是否已二进制的流的方式发送文件，这样整个上传内容php://input都为文件内容
                sendAsBinary: false,
                // 开起分片上传。 thinkphp的上传类测试分片无效,图片丢失;
                chunked: true,
                // 分片大小
                chunkSize: 512 * 1024,
                //最大上传的文件数量, 总文件大小,单个文件大小(单位字节);
                fileNumLimit: 50,
                fileSizeLimit: 500000 * 1024,
                fileSingleSizeLimit: this.fileSizeLimit,
                //配置生成缩略图的选项
                thumb: {
                    width: 160,
                    height: 120,
                    // 图片质量，只有type为`image/jpeg`的时候才有效。
                    quality: 90,
                    // 是否允许放大，如果想要生成小图的时候不失真，此选项应该设置为false.
                    allowMagnify: false,
                    // 是否允许裁剪。
                    crop: true,
                    // 为空的话则保留原有图片格式。
                    // 否则强制转换成指定的类型。
                    type: "image/jpeg"
                },
            });

            return webUploader;
        },

        bindEvent: function (bindedObj) {
            var me = this;
            //绑定文件加入队列事件;
            bindedObj.on('fileQueued', function (file) {
                me.createBox(file, bindedObj);

            });
            //进度条事件
            bindedObj.on('uploadProgress', function (file, percentage) {
                var $fileBox = $('#fileBox_' + file.id);
                var $diyBar = $fileBox.find('.diyBar');
                $diyBar.show();
                percentage = percentage * 100;
                me.showDiyProgress(percentage.toFixed(2), $diyBar);

            });
            //上传成功后触发事件;
            bindedObj.on('uploadSuccess', function (file, response) {
                var $fileBox = $('#fileBox_' + file.id);
                var $diyBar = $fileBox.find('.diyBar');
                $("#file_url_" + file.id).val(response);
                // $fileBox.removeClass('diyUploadHover');
                $diyBar.fadeOut(1000, function () {
                    $fileBox.children('.diySuccess').show();
                });
                // if (successCallBack) {
                //     successCallBack(response);
                // }
            });
            //上传失败后触发事件;
            bindedObj.on('uploadError', function (file, reason) {
                var $fileBox = $('#fileBox_' + file.id);
                var $diyBar = $fileBox.find('.diyBar');
                me.showDiyProgress(0, $diyBar, '上传失败!');
                var err = '上传失败! 文件:' + file.name + ' 错误码:' + reason;
                // if (errorCallBack) {
                //     errorCallBack(err);
                // }
            });

            //选择文件错误触发事件;
            bindedObj.on('error', function (code) {
                var text = '';
                switch (code) {
                    case  'F_DUPLICATE' :
                        text = '该文件已经被选择了!';
                        break;
                    case  'Q_EXCEED_NUM_LIMIT' :
                        text = '上传文件数量超过限制!';
                        break;
                    case  'F_EXCEED_SIZE' :
                        text = '文件大小超过限制!';
                        break;
                    case  'Q_EXCEED_SIZE_LIMIT' :
                        text = '所有文件总大小超过限制!';
                        break;
                    case 'Q_TYPE_DENIED' :
                        text = '文件类型不正确或者是空文件!';
                        break;
                    default :
                        text = '未知错误!';
                        break;
                }
                alert(text);
            });
        },
        //操作进度条;
        showDiyProgress: function (progress, $diyBar, text) {
            if (progress >= 100) {
                progress = progress + '%';
                text = text || '上传完成';
            } else {
                progress = progress + '%';
                text = text || progress;
            }

            var $diyProgress = $diyBar.find('.diyProgress');
            $diyProgress.width(progress).text(text);
        },

        //取消事件;
        removeLi: function ($li, file_id, webUploader) {
            $li.remove();
            webUploader.removeFile(file_id,true);
        },

        //左移事件;
        leftLi: function ($leftli, $li) {
            $li.insertBefore($leftli);
        },

        //右移事件;
        rightLi: function ($rightli, $li) {
            $li.insertAfter($rightli);
        },

        //创建文件操作div;
        createBox: function (file, webUploader) {
            var me = this;
            var $fileInput = $("#" + this.pickBtnId);
            var file_id = file.id;
            var $parentFileBox = $fileInput.parents(".upload-ul");
            var file_len = $parentFileBox.children(".diyUploadHover").length;

            //添加子容器;
            var li = '<li id="fileBox_' + file_id + '" class="diyUploadHover"> \
					<div class="viewThumb">\
					    <input type="hidden" name="url" id="file_url_' + file.id + '">\
					    <div class="diyBar"> \
							<div class="diyProgress">0%</div> \
					    </div> \
					    <p class="diyControl"><span class="diyLeft"><i></i></span><span class="diyCancel"><i></i></span><span class="diyRight"><i></i></span></p>\
					</div> \
				</li>';

            $parentFileBox.prepend(li);
            console.log($parentFileBox);

            var $fileBox = $parentFileBox.find('#fileBox_' + file_id);

            //绑定取消事件;
            var $diyCancel = $fileBox.find('.diyCancel').one('click', function () {
                me.removeLi($(this).parents('.diyUploadHover'), file_id, webUploader);
            });

            //绑定左移事件;
            $fileBox.find('.diyLeft').on('click', function () {
                me.leftLi($(this).parents('.diyUploadHover').prev(), $(this).parents('.diyUploadHover'));
            });

            //绑定右移事件;
            $fileBox.find('.diyRight').on('click', function () {
                me.rightLi($(this).parents('.diyUploadHover').next(), $(this).parents('.diyUploadHover'));
            });

            if (file.type.split("/")[0] != 'image') {
                var liClassName = me.getFileTypeClassName(file.name.split(".").pop());
                $fileBox.addClass(liClassName);
                return;
            }

            //生成预览缩略图;
            webUploader.makeThumb(file, function (error, dataSrc) {
                if (!error) {
                    $fileBox.find('.viewThumb').append('<img src="' + dataSrc + '" >');
                }
            });
        },
        bindUploadBtn: function (bindedObj) {
            $("#" + this.uploadBtnId).on('click', function () {
                bindedObj.upload();
            });
        },
        //获取文件类型;
        getFileTypeClassName: function (type) {
            var fileType = {};
            var suffix = '_diy_bg';
            fileType['pdf'] = 'pdf';
            fileType['ppt'] = 'ppt';
            fileType['doc'] = 'doc';
            fileType['docx'] = 'doc';
            fileType['jpg'] = 'jpg';
            fileType['zip'] = 'zip';
            fileType['rar'] = 'rar';
            fileType['xls'] = 'xls';
            fileType['xlsx'] = 'xls';
            fileType['txt'] = 'txt';
            fileType = fileType[type] || 'ppt';
            return fileType + suffix;
        },
        picBack:function (urls) {
            if(urls == "[]"){
                return;
            };
            var me = this;
            var urlsStr = urls.replace(/[\"\[\]]/g, "");
            urls = urlsStr.split(',')
            urls.forEach(function (url,idx) {
                url = url.replace( /^\s*/, '');
                var id = "YY_" + idx;
                var li = '<li id="fileBox_' + id + '" class="diyUploadHover"> \
					<div class="viewThumb">\
					    <input type="hidden" name="url" value="'+url+'" id="file_url_' + id + '">\
					    <div class="diyBar"> \
							<div class="diyProgress">0%</div> \
					    </div> \
					    <p class="diyControl"><span class="diyLeft"><i></i></span><span class="diyCancel"><i></i></span><span class="diyRight"><i></i></span></p>\
					</div> \
				</li>';
                var $parentFileBox = $("#upload-ul-yy");
                $parentFileBox.prepend(li);
                var $fileBox = $parentFileBox.find('#fileBox_' + id);
                //绑定取消事件;
                $fileBox.find('.diyCancel').one('click', function () {
                    $(this).parents('.diyUploadHover').remove();
                });

                //绑定左移事件;
                $fileBox.find('.diyLeft').on('click', function () {
                    me.leftLi($(this).parents('.diyUploadHover').prev(), $(this).parents('.diyUploadHover'));
                });

                //绑定右移事件;
                $fileBox.find('.diyRight').on('click', function () {
                    me.rightLi($(this).parents('.diyUploadHover').next(), $(this).parents('.diyUploadHover'));
                });
                $fileBox.find('.viewThumb').append('<img src="' + Feng.ctxPath + "/kaptcha/" + url + '" >');
            });
        },

    }


    window.$MultiPicUpload = $MultiPicUpload;
})();